<?php
include 'includes/header.php';
require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

// Get all brands for the dropdown and tabs
$brands_query = "SELECT b.*, COUNT(m.id) as model_count 
                 FROM brands b 
                 LEFT JOIN models m ON b.id = m.brand_id 
                 GROUP BY b.id 
                 ORDER BY b.name";
$brands = $db->query($brands_query)->fetchAll();

// Get first brand for initial active tab
$first_brand = $brands[0]['id'] ?? null;

// Handle model operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_model'])) {
        $name = sanitize_input($_POST['name']);
        $brand_id = $_POST['brand_id'];
        $query = "INSERT INTO models (name, brand_id) VALUES (?, ?)";
        $stmt = $db->prepare($query);
        
        if ($stmt->execute([$name, $brand_id])) {
            set_message('Model added successfully');
        } else {
            set_message('Error adding model', 'danger');
        }
    }

    if (isset($_POST['edit_model'])) {
        $id = $_POST['model_id'];
        $name = sanitize_input($_POST['name']);
        $brand_id = $_POST['brand_id'];
        $query = "UPDATE models SET name = ?, brand_id = ? WHERE id = ?";
        $stmt = $db->prepare($query);
        
        if ($stmt->execute([$name, $brand_id, $id])) {
            set_message('Model updated successfully');
        } else {
            set_message('Error updating model', 'danger');
        }
    }

    if (isset($_POST['delete_model'])) {
        $id = $_POST['model_id'];
        $query = "DELETE FROM models WHERE id = ?";
        $stmt = $db->prepare($query);
        
        if ($stmt->execute([$id])) {
            set_message('Model deleted successfully');
        } else {
            set_message('Error deleting model', 'danger');
        }
    }
}

// Get models for all brands with car count
$models_query = "SELECT m.*, b.name as brand_name, COUNT(c.id) as car_count 
                 FROM models m 
                 JOIN brands b ON m.brand_id = b.id 
                 LEFT JOIN cars c ON m.id = c.model_id
                 GROUP BY m.id
                 ORDER BY m.name";
$models_stmt = $db->prepare($models_query);
$models_stmt->execute();
$models = $models_stmt->fetchAll();

// Group models by brand
$models_by_brand = [];
foreach ($models as $model) {
    $models_by_brand[$model['brand_id']][] = $model;
}
?>

<div class="container-fluid py-4">
    <div class="row mb-4">
        <div class="col-12">
            <h2>Manage Models</h2>
        </div>
        <div class="col-md-6 text-end">
            <a href="./manage_brands.php" class="btn btn-primary">
                <i class="fas fa-plus"></i> Brands
            </a>
            <a href="./manage_cars.php" class="btn btn-primary">
                <i class="fas fa-plus"></i> Cars
            </a>
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModelModal">
                <i class="fas fa-plus"></i> Add New Model
            </button>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <!-- Brand Tabs -->
            <ul class="nav nav-tabs mb-3" role="tablist">
                <?php foreach ($brands as $index => $brand): ?>
                <li class="nav-item" role="presentation">
                    <button class="nav-link <?php echo $index === 0 ? 'active' : ''; ?>"
                            id="brand-tab-<?php echo $brand['id']; ?>"
                            data-bs-toggle="tab"
                            data-bs-target="#brand-<?php echo $brand['id']; ?>"
                            type="button"
                            role="tab">
                        <?php echo htmlspecialchars($brand['name']); ?>
                        <span class="badge bg-secondary"><?php echo $brand['model_count']; ?></span>
                    </button>
                </li>
                <?php endforeach; ?>
            </ul>

            <div class="tab-content" id="v-pills-tabContent">
                <?php foreach ($brands as $index => $brand): ?>
                <div class="tab-pane fade <?php echo $index === 0 ? 'show active' : ''; ?>"
                     id="brand-<?php echo $brand['id']; ?>"
                     role="tabpanel"
                     aria-labelledby="brand-tab-<?php echo $brand['id']; ?>">
                    <div class="card shadow">
                        <div class="card-body" style="max-height: 70vh; overflow-y: auto;">
                            <div class="table-responsive">
                                <table class="table">
                                    <thead>
                                        <tr>
                                            <th>Model Name</th>
                                            <th>Cars</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if (empty($models_by_brand[$brand['id']])): ?>
                                            <tr>
                                                <td colspan="3" class="text-center">No models found for this brand</td>
                                            </tr>
                                        <?php else: ?>
                                            <?php foreach ($models_by_brand[$brand['id']] as $model): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($model['name']); ?></td>
                                                    <td><?php echo $model['car_count']; ?></td>
                                                    <td>
                                                        <button type="button" 
                                                                class="btn btn-sm btn-primary edit-model"
                                                                data-id="<?php echo $model['id']; ?>"
                                                                data-name="<?php echo htmlspecialchars($model['name']); ?>"
                                                                data-brand="<?php echo $model['brand_id']; ?>"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#editModelModal">
                                                            <i class="fas fa-edit"></i>
                                                        </button>
                                                        <form method="POST" class="d-inline" 
                                                              onsubmit="return confirm('Are you sure?');">
                                                            <input type="hidden" name="model_id" 
                                                                   value="<?php echo $model['id']; ?>">
                                                            <button type="submit" name="delete_model" 
                                                                    class="btn btn-sm btn-danger">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        </form>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

<!-- Add Model Modal -->
<div class="modal fade" id="addModelModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Model</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Brand</label>
                        <select name="brand_id" class="form-select" required>
                            <?php foreach ($brands as $brand): ?>
                                <option value="<?php echo $brand['id']; ?>" 
                                        <?php echo $brand['id'] == $first_brand ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($brand['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Model Name</label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" name="add_model" class="btn btn-primary">Add Model</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Model Modal -->
<div class="modal fade" id="editModelModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Model</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="model_id" id="edit-model-id">
                    <div class="mb-3">
                        <label class="form-label">Brand</label>
                        <select name="brand_id" class="form-select" id="edit-model-brand" required>
                            <?php foreach ($brands as $brand): ?>
                                <option value="<?php echo $brand['id']; ?>">
                                    <?php echo htmlspecialchars($brand['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Model Name</label>
                        <input type="text" class="form-control" name="name" id="edit-model-name" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" name="edit_model" class="btn btn-primary">Update Model</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Edit Model Modal Handler
document.querySelectorAll('.edit-model').forEach(button => {
    button.addEventListener('click', function() {
        const id = this.getAttribute('data-id');
        const name = this.getAttribute('data-name');
        const brand = this.getAttribute('data-brand');
        
        document.getElementById('edit-model-id').value = id;
        document.getElementById('edit-model-name').value = name;
        document.getElementById('edit-model-brand').value = brand;
    });
});
</script>

